package top.kaoshanji.q1ch06c.aspects;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import top.kaoshanji.q1ch06c.model.Comment;

import java.util.Arrays;
import java.util.logging.Logger;

/**
 * @author kaoshanji
 * ^_^
 * create time 2025/4/29 10:17
 */
@Aspect
public class LoggingAspect {

    private Logger logger = Logger.getLogger(LoggingAspect.class.getName());

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    /**
     * 代码清单-q1ch06c-125页a：修改参数和返回值
     * @param joinPoint
     * @return
     */
    @Around("execution(* top.kaoshanji.q1ch06c.services.*.*(..))")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        Object [] arguments = joinPoint.getArgs();

        logger.info("...打印目标方法的名称：" + methodName + " ，参数：" + Arrays.asList(arguments));

        Comment comment = new Comment();
        comment.setAuthor("Jenny");
        comment.setText("Some other text!");
        Object [] newArguments = {comment};

        logger.info("....目标方法的新参数：" + comment.getText());

        Object returnedByMethod = joinPoint.proceed(newArguments);

        logger.info("...目标方法执行的结果：" + returnedByMethod);

        // 直接把目标方法的执行结果修改了
        return "FAILED";

    }

}
